//
//  Json.swift
//  medepend
//
//  Created by zhu xietong on 2023/11/30.
//

import Foundation

extension Dictionary{
    static func with(object:Any)->[String:Any]{
        var dictionary: [String: Any] = [:]
        let mirror = Mirror(reflecting: object)
        
        for child in mirror.children {
            if let key = child.label {
                if(type(of: child.value) is AnyObject.Type){
                    if let baseValue = child.value as? BaseValue{
                        dictionary[key] = baseValue.baseValue
                    }
                    else{
                        dictionary[key] = Dictionary.with(object: child.value)
                    }
                } else {
                    if let baseValue = child.value as? BaseValue{
                        dictionary[key] = baseValue.baseValue
                    }else{
                        dictionary[key] = child.value
                    }
                }
            }
        }
        
        return dictionary
    }
    
    public var jsonString:String{
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: [])
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                return jsonString
            }
        } catch {
            print("Error converting dictionary to JSON: \(error)")
        }
        return ""
    
    }
}
